package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.Catalog;
import cn.wolfcode.shop.mapper.CatalogMapper;
import cn.wolfcode.shop.mapper.ProductMapper;
import cn.wolfcode.shop.mapper.PropertyMapper;
import cn.wolfcode.shop.service.ICatalogService;
import cn.wolfcode.util.RedisConstants;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.MessageFormat;
import java.util.List;

@Service
public class CatalogServiceImpl implements ICatalogService {


    @Autowired
    private CatalogMapper catalogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public List<Catalog> selectAll() {
        return catalogMapper.selectAll();
    }

    @Override
    public List<Catalog> queryByPid(Long catalogId) {

        List<Catalog> catalogs = catalogMapper.queryByPid(catalogId);
        //遍历所有的分类

        for (Catalog catalog : catalogs) {

            String propertyKey = MessageFormat.format(RedisConstants.CATALOG_PROPERTY_COUNT, catalog.getId());
            //redis缓存中查询属性个数
            Integer propertyCount = (Integer) redisTemplate.opsForValue().get(propertyKey);
            if (propertyCount == null) {
                //根据catalog的id去统计属性的个数
                propertyCount = propertyMapper.getCountByCatalogId(catalog.getId());
                redisTemplate.opsForValue().set(propertyKey, propertyCount);
            }
            catalog.setPropertyCount(propertyCount);

            //redis缓存中查询商品个数
            String productKey = MessageFormat.format(RedisConstants.CATALOG_PRODUCT_COUNT, catalog.getId());
            Integer productCount = (Integer) redisTemplate.opsForValue().get(productKey);
            if (productCount == null) {
                productCount = productMapper.getProductCountByCatalogId(catalog.getId());
                redisTemplate.opsForValue().set(productKey,productCount);
            }
            catalog.setProductCount(productCount);
        }
        return catalogs;
    }

    @Override
    public void saveOrUpdate(Catalog catalog) {

        if (catalog.getId() == null) {

            catalogMapper.insert(catalog);

            //判断当前插入子节点的父节点状态, 如果isParent状态为0(false), 那么该节点的isParent设置为true,然后再进行更新
            Catalog parentcCatalog = catalogMapper.selectByPrimaryKey(catalog.getPId());

            //isParent 为0 , 即false,  再取反就为true 执行if条件
            if (!parentcCatalog.isParent()) {
                parentcCatalog.setParent(true);
                catalogMapper.updateByPrimaryKey(parentcCatalog);
            }
        } else {
            catalogMapper.updateByPrimaryKey(catalog);
        }
        refreshCache();
    }

    @Override
    public void deleteByCId(Long catalogId) {

        //获取要删除节点的父节点
        Catalog catalog = catalogMapper.getParentCatalog(catalogId);

        //查询父节点包含多少个子节点, 判断为1的话, 执行删除后, 该节点的is_Parent要改为0
        Integer childCount = catalogMapper.getChildCountById(catalogId);
        if (childCount == 1) {
            catalog.setParent(false);
            catalogMapper.updateByPrimaryKey(catalog);
        }

        catalogMapper.deleteByPrimaryKey(catalogId);

        refreshCache();
    }

    @Override
    public void batchUpdateSort(List<Long> ids) {

        //遍历数组, 拿到所有元素的信息
        for (int i = 0; i < ids.size(); i++) {

            Catalog catalog = catalogMapper.selectByPrimaryKey(ids.get(i));
            catalog.setSort(i + 1);
            catalogMapper.updateByPrimaryKey(catalog);
        }

        refreshCache();
    }


    /**
     * redis中查询缓存
     *
     * @return
     */
    @Override
    public String selectAllByCache() {

        //从redis中查询分类目录的缓存
        String allCatalog = (String) redisTemplate.opsForValue().get(RedisConstants.CATALOG_ALL);
        System.out.println(allCatalog);

        //如果查询不到,从数据库中查询,放入到redis缓存中
        if (allCatalog == null) {
            allCatalog = refreshCache();
        }
        //如果能查询,直接返回
        return allCatalog;
    }

    /**
     * 更新redis缓存
     *
     * @return
     */
    public String refreshCache() {

        List<Catalog> catalogList = catalogMapper.selectAll();
        //转成JSON格式返回给前端
        String catalogJsonString = JSON.toJSONString(catalogList);
        //设置key 和 value
        redisTemplate.opsForValue().set(RedisConstants.CATALOG_ALL, catalogJsonString);
        return catalogJsonString;
    }


}
